package logic

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"group-card/common/constant"
	"group-card/common/request"
	"group-card/model/entity"
	"group-card/rpc/card/cardclient"
	"group-card/rpc/card/internal/svc"
)

type PublishStopLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPublishStopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PublishStopLogic {
	return &PublishStopLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//region TODO: 批次停用 Author:LiuYanLin Date:2023/04/05 周三 13:24

func (l *PublishStopLogic) PublishStop(in *cardclient.PublishStopRequest) (*cardclient.PublishStopResponse, error) {
	var ctx context.Context

	//region TODO: 获取卡片发行记录详情 Author:LiuYanLin Date:2023/07/03 周一 14:13
	cardPublishResp, err := l.svcCtx.PublishModel.GetCardPublish(ctx, &entity.CardPublishReq{
		Id: in.Id,
		BaseReq: request.BaseReq{
			Columns: "service_number,status",
		},
	})
	if err != nil {
		return nil, err
	}
	if cardPublishResp.Status == constant.CardPublishStatus10 {
		return nil, errors.New("请先发行")
	}
	if cardPublishResp.Status == constant.CardPublishStatus40 {
		return nil, errors.New("请勿重复批次停用")
	}
	//endregion

	db := l.svcCtx.Orm.NewSession()
	db.Begin()
	defer db.Close()

	//region TODO: 修改卡片发行记录(事务) Author:LiuYanLin Date:2023/07/03 周一 13:53
	err = l.svcCtx.PublishModel.UpdateCardPublishDb(ctx, db, &entity.CardPublishReq{
		Id:     in.Id,
		Status: constant.CardPublishStatus40,
		BaseReq: request.BaseReq{
			Columns: "status",
		},
	})
	if err != nil {
		db.Rollback()
		return nil, err
	}
	//endregion

	//region TODO: 删除卡片绑定记录(事务) Author:LiuYanLin Date:2023/04/04 周二 17:31
	err = l.svcCtx.BindingModel.DeleteCardBindingDb1(ctx, db, &entity.CardBindingReq{
		ServiceNumber: cardPublishResp.ServiceNumber,
	})
	if err != nil {
		db.Rollback()
		return nil, err
	}
	//endregion

	db.Commit()

	return &cardclient.PublishStopResponse{}, nil
}

//endregion
